﻿using System;
using System.Drawing;
using System.Windows.Forms;
using CppProject;

namespace BackEndProcessorInterface
{
    public partial class ToolBarPanel : Form
    {
        private static bool _CLOSE;
/*        private const int MOUSE_DEFAULT = 0;
*/
        //TODO: change ComboBogCheckFlag and then make fparam local!
        private static readonly bool[] fparam = new bool[3];
        private static CppController controller;
        private readonly MainMenu _menu;      

        #region Public

        public ToolBarPanel(MainMenu menu, CppController cppController)
        {
            InitializeComponent();
            _menu = menu;
            //TODO: change Item!
            comboBoxCheckBoxFlagsStyle.AddItem("Draw F", true);
            comboBoxCheckBoxFlagsStyle.AddItem("Draw Df/Dx", true);
            comboBoxCheckBoxFlagsStyle.AddItem("Draw Df/Dy", true);

            fparam[0] = true;
            fparam[1] = true;
            fparam[2] = true;

            var toolTip = new ToolTip { AutomaticDelay = 1000 };
            toolTip.SetToolTip(buttonZoomAdd, "Приблизить");
            toolTip.SetToolTip(buttonZommRemove, "Уменьшить");
            toolTip.SetToolTip(buttonIsolineApply, "Применить к изолиниям");
            toolTip.SetToolTip(IsolinesScale,"Установить диапозон изменения изолиний");
           // toolTip.SetToolTip(buttonGraphicsApply, "Применить к графике");

            gradientTrackBarToolColor.Apply += gradientTrackBarToolColor_Apply;
            gradientTrackBarToolColor.Scale += gradientTrackBarToolColor_Scale;

            controller = cppController;

            gradientTrackBarToolColor_Apply(gradientTrackBarToolColor);
        }

        static void gradientTrackBarToolColor_Scale(GradientTrackBarControlLibrary.GradientTrackBar iTracBar)
        {
            var p = controller.MaxMinValue();
                
            iTracBar.F1 = p.Y;
            iTracBar.F2 = p.Y + (p.X - p.Y) * 0.33f;
            iTracBar.F3 = p.Y + (p.X - p.Y) * 0.66f;
            iTracBar.F4 = p.X;

            gradientTrackBarToolColor_Apply(iTracBar);
        }

        public bool CLOSE
        {
            set { _CLOSE = value; }
            get { return _CLOSE; }
        }    
        public Control GetControl(String name)
        {
            var myControl = Controls.Find(name, true);
            return myControl[0];
        }
        public void SetControlState(String name,Object value)
        {
            var toolFormControl = Controls.Find(name, true)[0];
            if(toolFormControl is CheckBox)
                ((CheckBox) toolFormControl).Checked = (bool) value;            
        }
        public void SetMousePointer(String name, Object value)
        {
            switch (name)
            {
                case "toolStripButtonMouseDefault":
                  //  toolStripButtonFlag.Checked = !(toolStripButtonMouseDefault.Checked = (bool)value);                    
                    toolStripButtonFlag.Enabled = !(toolStripButtonMouseDefault.Enabled = !(bool)value);
                    groupBoxFlags.Enabled = !((bool)value);               
                    break;
                case "toolStripButtonFlag":
                   // toolStripButtonMouseDefault.Checked = !(toolStripButtonFlag.Checked = ((bool)value));
                    toolStripButtonMouseDefault.Enabled = !(toolStripButtonFlag.Enabled = !(bool)value);
                    groupBoxFlags.Enabled = ((bool)value);                 
                    break;
            }
        }
        public void _BorderVisible(bool val)
        {
            FormBorderStyle = val ? FormBorderStyle.None : FormBorderStyle.Sizable;
        }      
        public PConfig GetGraphicsConfig() 
        {
            var graphic =  new PConfig{                                  
                {"BoxAxis", checkBoxAxis.Checked},
                {"BoxMesh", checkBoxMesh.Checked},
                {"BoxMeshFI", checkBoxMeshFI.Checked},
                {"BoxIsoline", checkBoxIsoline.Checked},
                {"BoxFlags", checkBoxFlags.Checked} 
            };            
            graphic.Name = "Graphics";
            return graphic;
        }

        public string IsolinesToString()
        {
            double isolineMin;
            double isolineMax;
            int isolineRelax;
         
                Double.TryParse(textBoxIsolineMin.Text, out isolineMin);
                Double.TryParse(textBoxIsolineMax.Text, out isolineMax);
                Int32.TryParse(textBoxIsolineRelax.Text,out isolineRelax);
             

                return isolineMin + "|" + isolineMax + "|" + isolineRelax;
        }

        public void IsolinesFromString(string isolinesString)
        {
            double isolineMin;
            double isolineMax;
            int isolineRelax;
            
                string[] isolinesArray = isolinesString.Split('|');

                Double.TryParse(isolinesArray[0], out isolineMin);
                Double.TryParse(isolinesArray[1], out isolineMax);
                Int32.TryParse(isolinesArray[2], out isolineRelax);
           

            textBoxIsolineMin.Text = String.Format("{0:E2}", isolineMin);
            textBoxIsolineMax.Text = String.Format("{0:E2}", isolineMax);
            textBoxIsolineRelax.Text = isolineRelax.ToString();
            IsolineApply();
        }

        public string ColorScaleToString() { return gradientTrackBarToolColor.ToString(); }
        public void ColorScaleFromString(string colorScaleString) { gradientTrackBarToolColor.FromString(colorScaleString); }
       
        public void IsolineApply()
        {
            double isolineMin;
            double isolineMax;
            int isolineRelax;

            Double.TryParse(textBoxIsolineMin.Text, out isolineMin);
            Double.TryParse(textBoxIsolineMax.Text, out isolineMax);
            Int32.TryParse(textBoxIsolineRelax.Text, out isolineRelax);

            _menu.SetIsolineSettings(new[] { isolineMin, isolineMax, isolineRelax });
            controller.SetIsoLines(isolineMin, isolineMax, isolineRelax);
        }
        #endregion
        
        #region Private

        private void checkBoxGraphics_CheckedChanged(object sender, EventArgs e)
        {
            switch (((CheckBox)sender).Name)
            {
                case "checkBoxAxis":
                    _menu.SetGraphicsMenuItemCheck(0, ((CheckBox)sender).Checked);
                    break;
                case "checkBoxMesh":
                    _menu.SetGraphicsMenuItemCheck(1, ((CheckBox)sender).Checked);
                    break;
                case "checkBoxMeshFI":
                    _menu.SetGraphicsMenuItemCheck(2, ((CheckBox)sender).Checked);
                    break;
                case "checkBoxIsoline":
                    _menu.SetGraphicsMenuItemCheck(3, ((CheckBox)sender).Checked);
                    break;
                case "checkBoxFlags":
                    _menu.SetGraphicsMenuItemCheck(4, ((CheckBox)sender).Checked);
                    break;
                    
            }
        }
        private static void gradientTrackBarToolColor_Apply(GradientTrackBarControlLibrary.GradientTrackBar iTracBar)
        {
            controller.SetColorScale(iTracBar.FunctionArray, iTracBar.ColorArray);
        }
        /*
        private void buttonGraphicsApply_Click(object sender, EventArgs e)
        {
           _menu.GraphicsSettingApply(new[]{checkBoxAxis.Checked,checkBoxMesh.Checked,
            checkBoxMeshFI.Checked, checkBoxIsoline.Checked,checkBoxFlags.Checked});
        }
        */
        private void buttonZommRemove_Click(object sender, EventArgs e)
        {
            _menu.ZoomRemove();
        }

        private void buttonZoomAdd_Click(object sender, EventArgs e)
        {
            _menu.ZoomAdd();
        }
        
        private void ToolBarPanel_FormClosing(object sender, FormClosingEventArgs e){
            e.Cancel = !CLOSE;
            if (!CLOSE)            
                Hide();       
        }

        private void buttonIsolineApply_Click(object sender, EventArgs e)
        {
            IsolineApply();
        }
/*
        private void ShowErrorBox(String message)
        {
            MessageBox.Show(this, message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
*/
        private void toolStripButtonMouse_Click(object sender, EventArgs e)
        {
            switch (((ToolStripButton)sender).Name)
            {
                case "toolStripButtonMouseDefault":
                    toolStripButtonFlag.Checked = !(toolStripButtonMouseDefault.Checked = true);
                    toolStripButtonFlag.Enabled = !(toolStripButtonMouseDefault.Enabled = false);
                    groupBoxFlags.Enabled = false;
                    buttonAddFlag.Enabled = true;
                    _menu.SetTask("Default regime");
                    break;
                case "toolStripButtonFlag":
                    toolStripButtonFlag.Checked = !(toolStripButtonMouseDefault.Checked = false);
                    toolStripButtonFlag.Enabled = !(toolStripButtonMouseDefault.Enabled = true);
                    groupBoxFlags.Enabled = true;
                    _menu.SetTask("Flag regime");
                    break;
            }
            _menu.PaintMouseFlag(toolStripButtonFlag.Checked);
            _menu.MousePointerSettings(0, toolStripButtonMouseDefault.Checked);
            _menu.MousePointerSettings(1, toolStripButtonFlag.Checked);   
        }
      

        private void comboBoxCheckBoxFlagsStyle_CheckStateChanged(object sender, EventArgs e)
        {
            var item = (ComboBogCheckFlag.CheckComboBoxItem)sender;
            switch (item.Text)
            {
                case "Draw F":
                    fparam[0] = item.CheckState;
                    break;
                case "Draw Df/Dx":
                    fparam[1] = item.CheckState;
                    break;
                case "Draw Df/Dy":
                    fparam[2] = item.CheckState;
                    break;
            }

            controller.SetFlagsMode(fparam[0], fparam[1], fparam[2]);
        }

        private void buttonAddFlag_Click(object sender, EventArgs e)
        {
            _menu.GetFlagOption(fparam);
            controller.MouseInFlagMode = true;
            //buttonRemoveFlag.Enabled = true;
            buttonAddFlag.Enabled = false;
            _menu.SetTask("Put flags...");
        }

        private void buttonRemoveFlag_Click(object sender, EventArgs e)
        {
             _menu.DeleteLastFlagOption();
   //            controller.MouseInFlagMode = false;
//             buttonRemoveFlag.Enabled = false;
//             buttonAddFlag.Enabled = true;
              controller.ClearFlags();
            _menu.SetTask("Cancel flags...");
        }
        #endregion
        public  void ScaleGrad(string controlname)
        {
            if(controlname.Equals("getisol"))
            IsolinesScale.PerformClick();
            if(controlname.Equals("getgrad"))
                gradientTrackBarToolColor_Scale(gradientTrackBarToolColor);
            
        }

        private void IsolinesScale_Click(object sender, EventArgs e)
        {
            var p = controller.MaxMinValue();
            textBoxIsolineMin.Text = String.Format("{0:E2}", p.Y);
            textBoxIsolineMax.Text = String.Format("{0:E2}", p.X);
            IsolineApply();           
        }
        public void AddFlag()
        {
            buttonAddFlag.PerformClick();

        }

        public void RemoveFlags()
        {
            buttonRemoveFlag.PerformClick();
        }

        private void ToolBarPanel_Load(object sender, EventArgs e)
        {
           // var screenwidth = SystemInformation.PrimaryMonitorSize.Width;
            var screenheight = SystemInformation.PrimaryMonitorSize.Height;
            MaximumSize = new Size(Width, screenheight*7/8);
            MinimumSize = new Size(Width*7/8, Height * 4/5);
        }
        private void ToolBarPanel_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (ModifierKeys == Keys.Control)
                //Ctrl+B
                if ((e.KeyChar & 0xF) == 2)
                    FormBorderStyle = (FormBorderStyle == FormBorderStyle.None) ? FormBorderStyle.Sizable : FormBorderStyle.None;
        }
        
    }
}
